package cn.majingjing.core.tool;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

public class FreemarkerUtils {

	private static Configuration cfg;

	static {
		cfg = new Configuration();
		cfg.setDefaultEncoding("UTF-8");
		cfg.setOutputEncoding("UTF-8");
		cfg.setClassForTemplateLoading(FreemarkerUtils.class, "/template/");
		cfg.setObjectWrapper(new DefaultObjectWrapper());
	}

	public static void render(Map<String, Object> data, String templateFile, File outputFile) {
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			Template temp = cfg.getTemplate(templateFile, "utf-8");
			fw = new FileWriter(outputFile);
			bw = new BufferedWriter(fw);
			temp.process(data, bw);
			bw.flush();
		} catch (Exception e) {
			System.err.println((String.format("将数据%1$s通过FreeMarker模板%2$s生成文件%3$s失败", data, templateFile, outputFile)));
		} finally {
			if (bw != null) {
				try {
					bw.close();
				} catch (IOException e) {
					System.err.println("BufferedWriter关闭异常");
				}
			}
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
					System.err.println("FileWriter关闭异常");
				}
			}
		}
	}

	public static String render(Map<String, Object> data, String templateFile) {
		FileWriter fw = null;
		BufferedWriter bw = null;
		try {
			Template temp = cfg.getTemplate(templateFile,"utf-8");

			Writer out = new StringWriter();
			temp.process(data, out);
			System.out.println("++++++++++++++++++++++++++++++++++++++\n" + out.toString());
			return out.toString();
		} catch (Exception e) {
			System.err.println(String.format("将数据%1$s通过FreeMarker模板%2$s失败", data, templateFile));
			e.printStackTrace();
		} finally {
			if (bw != null) {
				try {
					bw.close();
				} catch (IOException e) {
					System.err.println("BufferedWriter关闭异常");
				}
			}
			if (fw != null) {
				try {
					fw.close();
				} catch (IOException e) {
					System.err.println("FileWriter关闭异常");
				}
			}

		}
		return null;
	}
}
